<?php
namespace app\dlc\controller;


use app\dlc\common\createHelper\Common;
use app\dlc\common\form\Form;
use think\Db;
use think\Request;

class CommonController extends BaseController
{
    protected $map = [];//组装各种条件
    protected $mapRole = [];//只组装 判断角色权限的条件
    protected $roleName;
    protected $role_table_id;//shop角色，shop表的id     uid  是admin表的id
    protected $form = false;
    protected $formAddArray = false;
    protected $backUrl;
    protected $back = true;//编辑页面，默认有返回按钮  false 可去掉返回按钮
    protected $admin = false;//判断是否后台总管理员
    protected $check = false; //true 表示列表中，显示选择框
    protected $title;//导航条下面的标题
//    protected $data;//编辑或者添加的时候，用来重组数据，不适用原来的数据
    protected $selfUrl;
    protected $excel = false;
    public  static $roleList = ['admin','agent','shop'];//角色，对应的表名
    protected $roleIds = ['agent'=>2,'shop'=>3];//添加后台角色的时候，使用到该数组  2是对应表role  的id
    private $map_id = 'user_id,device_id,form_id,door_id,form_id,form_list_id,replenishment_id,type_id';//url 如果有这个参数，自动转为map 所以需要的条件
    private $button = [
        'delete' => ['color' => 'btn-danger', 'ico' => 'fa-trash-o', 'ajax' => true, 'data-type' => 'del', 'display' => 0],//ini=0 表示没有初始化   删除
        'del' => ['color' => 'btn-danger', 'ico' => 'fa-trash-o', 'ajax' => true, 'data-type' => 'del', 'display' => 0],//ini=0 表示没有初始化   删除
        'edit' => ['color' => 'btn-success', 'ico' => 'fa-edit', 'ajax' => false, 'display' => 0],//编辑
        'add' => ['color' => 'btn-primary', 'ico' => 'fa-plus', 'ajax' => false],//添加
        'money' => ['color' => 'btn-purple', 'ico' => 'fa-money', 'ajax' => false, 'display' => 0],//有关金钱
        'device' => ['color' => 'btn-primary', 'ico' => 'fa-eye', 'ajax' => false, 'display' => 0],//设备
        'history' => ['color' => 'btn-info', 'ico' => 'fa-history', 'ajax' => false, 'display' => 0],//历史记录
        'goods' => ['color' => 'btn-info', 'ico' => 'fa-shopping-cart', 'ajax' => false, 'display' => 0],//商品
        'send' => ['color' => 'btn-info', 'ico' => 'fa-send-o', 'ajax' => false, 'display' => 0],//发送
        'users' => ['color' => 'btn-success', 'ico' => 'fa-users', 'ajax' => false, 'display' => 0],//更多用户
        'picture' => ['color' => 'btn-info', 'ico' => 'fa-file-picture-o', 'ajax' => false, 'display' => 0],//图片
        'disable' => ['color' => 'btn-danger', 'ico' => 'fa-ban', 'ajax' => true, 'data-type' => 'del', 'display' => 0],//禁用
        'enable' => ['color' => 'btn-info', 'ico' => 'fa-check', 'ajax' => true, 'data-type' => 'del', 'display' => 0],//启用
        'back' => ['color' => 'btn-primary', 'ico' => 'fa-mail-reply'],//返回
        'excelDownload' => ['color' => 'btn-primary excel', 'ico' => 'fa-download','ajax' => 3],//表下载
    ];
    private $headButton = [];
    private $listButton = [];
    private $search = [];
    private $searchName = [];
    private $sort = 0;
    protected $className;
    public function _initialize()
    {

        parent::_initialize(); // TODO: Change the autogenerated stub
        $request= Request::instance();
        define("CONTROLLER_NAME", $request->controller());
        define("ACTION_NAME", $request->action());
        define("MODULE_NAME", 'Dlc');
        define("CONTROLLER_URL", '/Dlc/'.CONTROLLER_NAME.'/');

        //面包屑  start  1.获取当前的controllerName  role_oath模糊查找url   再匹配function，找到对应的oid  找父级oid
//        $request= Request::instance();
        $this->className = $this->uncamelize(CONTROLLER_NAME);
        $controller_name = CONTROLLER_NAME;
        $url_s  = CONTROLLER_NAME.'/'.ACTION_NAME;
        for ($i=0; $i < 1; $i++) {
            $url = Db::name('role_oath')->where(['url' => $url_s])->find();//有可能controller前面一部分有相识
            if ($url) break;
            $count =  explode('edit',strtolower(ACTION_NAME));
            $url_s  = CONTROLLER_NAME.'/'.$count[0];
            $url = Db::name('role_oath')->where(['url' => $url_s])->find();//有可能controller前面一部分有相识
            if ($url) break;
            $url_s = CONTROLLER_NAME.'/index';
            $url = Db::name('role_oath')->where(['url' => $url_s])->find();//有可能controller前面一部分有相识
            if ($url) break;
        }

        $p_url = Db::name('role_oath')->where(['oath_id' => $url['parent_id']])->find();
        $this->bread_ininput([$p_url['name'], $url['name']]);
        $this->title = $url['name']?:'无标题';
        $this->assign('uid', $this->uid);
        //面包屑 end

        //角色管理
        if ($this->uid != 1) {//非主管理员登录
            foreach (self::$roleList as $value){

                if (!in_array($value,['admin'])){
                    $fields = Common::getTableInfo($value);
                    if (in_array('aid',$fields)){
                        $res = Db::name($value)->where(['aid' => $this->uid])->value('id');
                        if ($res) {
                            $this->roleName = $value;
                            $v = $value.'_id';
                            $this->$v = $res;
                            $this->role_table_id = $res;
                            $this->assign($value.'_id', $res);
                            $this->map[$value.'_id'] = $res;
                            $this->mapRole[$value.'_id'] = $res;
                        }
                    }else{
                        echo $value.'该角色没有aid字段';
                    }

                }
            }
        }else{
            $this->admin = true;
            $this->roleName = 'admin';
        }

        //启动excel导出
        if (input('excel')){
            $this->excel = true;
            self::$page = '1,10000';
        }
        $role_id_list = [];
        foreach (self::$roleList as $key => $item) {
            if ($item!='admin')   $role_id_list[] = $this->uncamelize($item) . '_id';
        }

        $map_id = array_merge(explode(',',$this->map_id),$role_id_list);
        $post = input('post.');
        foreach ($map_id as $key => $value) {
            $input_value = $post[$value]?:input($value);//如果是数组的要用post的方式获取，如果url的要用input获取
            if ($input_value&&!is_array($input_value)) {//避免提交的是数组
                $valueName = $this->uncamelize($value);//驼峰命名转下划线命名
                $this->map[$valueName] = $input_value;
                $this->assign($valueName, $input_value);
                $this->parameter[$valueName] = $input_value;
            };
        }

        if (input('id'))  $this->assign('id', input('id'));
        $this->selfUrl = MODULE_NAME . '/' . CONTROLLER_NAME . '/' . ACTION_NAME;
        $this->assign('classNameId', $this->uncamelize(CONTROLLER_NAME) . '_id');
        $this->assign('className', $this->uncamelize(CONTROLLER_NAME));
        $this->assign('selfUrl', $this->selfUrl);//获取当前的url，替换搜索位置的url
        $this->assign('thisUrl', $request->url());//获取当前的url，替换搜索位置的url
        $this->assign('p', self::$p);
        $this->assign('empty', '<tr><td colspan="16" style="line-height:32px;text-align:center;">暂无数据！</td></tr>');
//        $this->assign('empty','暂无数据！');

    }

    public function loading($value=true){
        $this->assign('check', $this->check);// 列表是否可以勾选
        foreach ($this->listButton as $key=>$user) {
            if ($user['display']==1){
                $ages[] = $user['sort'];
            }else{
                unset($this->listButton[$key]);
            }
        }
        if (is_array($ages)){
            array_multisort($ages, SORT_ASC, $this->listButton);//排序
        }

        //        默认搜索  不关联，准确搜索
        foreach ($this->search as $key=>$value){
            $search_key = explode('|',$value['key']);
//            dump($search_key);
            if (count($search_key)>1){
                $search_key = array_flip($search_key);
                $like = $search_key[1]?1:0;
                unset($search_key[1]);
                $search_key = array_flip($search_key);//调换key和value  删除1的值
                if (count($search_key)==1){
                    $this->search($search_key[0],$like);
                }elseif (count($search_key)==2){
                    $pk = $this->getPk($search_key[0]);//获取主键
                    $thisKey = $search_key[0].'_id';
                    $vv = implode('-',$search_key);
                    $this->lqSearch($search_key[0],$pk,$search_key[1],$like,$thisKey,$vv);
                }
                $this->search[$key]['key'] = implode('-',$search_key);
            }else{
                $this->search($value['key']);
            }

        }
//        dump($this->search);
//        dump($this->headButton);
        $this->assign('title', $this->title);
        $this->assign('buttonWidgets', $this->listButton);
        $this->assign('searchWidgets', $this->search);
        $this->assign('headButtonWidgets', $this->headButton);
//        dump($this->headButton);

    }

    /**
     * 判断是否有权限，针对按钮 有返回true
     * @return role  角色
     */
    private  function isJurisdiction($role){
        if ($role){
            $role = explode(',',$role);
            if (in_array($this->roleName,$role)) return true;
            return false;
        }else{
            return true;
        }
    }
    /**
     *
     * 头部按钮小部件
     * @param  string $role 使用者的角色  admin,area,clerk
     * @param  string $key 输入框的name，使用button数组里面的key
     * @param  string $name 输入框中文名
     * @param  string $url 对应的url
     * @param  string $ajax 是否异步跳转 0 loader跳转  1异步请求  2不跳转，无异步，弹出窗口 3不跳转，无异步，4.弹出新窗口
     * @param  bool $check 是否有勾选（应用场景：勾选删除，勾选发送优惠劵）
     */
    public function headBotton($role, $key, $name, $url='' ,$ajax = false, $windowsContent = false, $check=false)
    {
        if (!$this->check){  //只有有1次就为true
            if ($check) $this->check = true;
        }
        $button = $this->button[$key];
        $button['role'] = $this->isJurisdiction($role);
        $button['key'] = $key;
        $button['name'] = $name;
        if ($key=='excelDownload'){
            $button['url'] = CONTROLLER_URL.ACTION_NAME.'/excel/1';
        }else{
            $button['url'] = $url;
        }

        if ($check) $ajax = 3;
        if ($ajax) {
//            $button['data-type'] = $this->button[$key]['data-type']?:'confirm';
            $button['data-type'] = '';
            $button['ajax'] = $ajax;
            if ($ajax==2) unset($button['data-type']);
        }
        if ($windowsContent) $button['windowsContent'] = $windowsContent;
        $button['check'] = $check;
        $this->headButton[] = $button;

    }

    /**
     * 头部搜索小部件
     * @param  string $role 使用者的角色  admin,area,clerk
     * @param  string $key 输入框的name    name|1  name模糊查找    shop|name  shop表的name 关联查询      shop|name|1  shop表name的关联模糊查询
     * @param  string $name 输入框中文名
     * @param  string $type 输入框类型 1.input  2.select 3.时间控件
     * @param  string $data select的数组数据
     */
    public function headSearch($role, $key, $name, $type, $data = [])
    {
        $search['role'] = $this->isJurisdiction($role);
        $search['key'] = $key;
        $search['name'] = $name;
        $search['type'] = $type;
        $search['data'] = $data;
        $this->search[] = $search;

    }

    /**
     *
     * 头部导航按钮部件
     * @param  string $arr  数组
     * @param  string $key  自动加载到map中，条件
     * @param  string $add  是否显示添加按钮
     */
    public function headNav($arr,$key,$add=false){
        if (!is_array($arr)) {echo '请传入数组';die;}
        $keys = array_keys($arr);
        $type_id = input('type_id')?:$keys[0];
        $this->title = $arr[$type_id];
        $this->assign('type_id',$type_id);
        $this->map[$key] = $type_id;
        $navList = [];
        foreach ($arr as $key => $value) {
            $navList[$key]['id'] = $key;
            $navList[$key]['name'] = $value;
            $navList[$key]['url'] = '/Dlc/'.$this->className.'/index/type_id/'.$key;
        }
        $this->assign('navList',$navList);
        if ($add){
            $this->headBotton('','add','添加','/dlc/'.$this->className.'/edit/type_id/'.$type_id);
        }

    }

    /**
     * 列表按钮小部件
     * @param  string $role 使用者的角色  admin,area
     * @param  string $key 按钮的name
     * @param  string $name 按钮中文名
     * @param  string $url 跳转到的url
     * @param  string $ajax 是否异步跳转 0 loader跳转  1异步请求  2不跳转，无异步，弹出窗口 3不跳转，无异步，4.弹出新窗口
     * @param  string $windowsContent 弹窗显示内容
     * @param  string $color 颜色
     * @param  string $ico 图标
     * @param  string $condition 显示的条件，比如 ['status','=',2]  status ==2  的时候显示该按钮
     * @param  array $addData 增加的数据属性，['id', 'name'] 对应属性 data-id data-name
     * @param  array $bindEvents 绑定事件，['id', 'name'] 对应属性 data-id data-name     ['onClick' => 'openNewWindows'] 异步打开新窗口
     */
    public function listBotton($role, $key, $name, $url, $ajax = false, $windowsContent = false, $color = false, $ico = false, $condition = false, $bindEvents = [], $addData = [])
    {//按钮key，按钮名称，按钮链接，按钮颜色
        if (count($bindEvents)==0 && $ajax==2){
            $bindEvents = ['onClick' => 'openNewWindows'];
        }
        $this->sort++;
        $button = $this->button[$key];
        $button['role'] = $this->isJurisdiction($role);
        $button['display'] = 1;
        $button['name'] = $name;
        $button['url'] = $url;
        $button['sort'] = $this->sort;
        if ($condition) $button['condition'] = $condition;
        if ($ajax) {
            $button['ajax'] = $ajax;
            if ($ajax==2) unset($button['data-type']);
        }
        if ($windowsContent) {
            if (!$button['data-type']) $button['data-type'] = 'confirm';
            $button['windowsContent'] = $windowsContent;
        }
        if ($color) $button['color'] = $color;
        if ($ico) $button['ico'] = $ico;
        $button['addData'] = $addData;
        $button['bindEvents'] = $bindEvents;
        $this->listButton[] = $button;
    }


    /**
     * 列表 某个字段的输入框   输入后的内容也是post回来这里
     * @param  string $role 使用者的角色  admin,area
     * @param  string $id
     * @param  string $key 字段名
     * @param  string $value 字段值
     */
    public function listInput($role = '',$id = '',$key = '',$value = ''){
        if (!$_POST){
            $res = $this->isJurisdiction($role);
            if (!$res) return $value;//如果没有权限，返回原值
            return '<input type="text" class="listInput" name="' . $key . '" value="' . $value . '" title="' . $value . '" style="width:100%;" data-id="' . $id . '">';
        }else{
            //处理post回来的数据
            $post = input('post.');
            $res = Db::name($this->className)->update($post);
            if ($res)  admin_return(1,'成功');
            admin_return(0,'失败');
        }
    }

    //如果是角色加载的话，需要判断这个表中，是否有存角色的id
    public function map($table=false){
        if (!$table) $table = CONTROLLER_NAME;
        $table =  $this->uncamelize($table);
        $map = $this->map;
        $fields = Common::getTableInfo($table);
        foreach ($map as $key => $item) {
            if (in_array(str_replace('_id','',$key),self::$roleList)){
                if (!in_array($key,$fields)){
                    unset($map[$key]);
                }
            }
        }
        return $map;

    }

    //组装面包屑
    public function bread_ininput($data)
    {
        if (!is_array($data)) {
            $res1 = explode(',', $data);
            $res2 = explode('-', $data);
            $data = count($res1) > count($res2) ? $res1 : $res2;

        }
        $bread = [];
        foreach ($data as $key => $value) {
            $bread[$key]['name'] = $value;
        }
        $this->assign('breadhtml', $this->getBread($bread));
    }

    public function search($keyword, $like = 0)
    {//搜索的关键词 该表的某个字段，
        $value = trim(input($keyword));
        if (strpos($keyword,'time')){
            $play_time = input($keyword) ? input($keyword) : '';
            if ($play_time) {
                $timeArr = explode(" - ", $play_time);
                if (count($timeArr) < 2) {
                    $timeArr = explode("+-+", $play_time);
                }

                $stime = strtotime($timeArr[0]);
                $etime = strtotime($timeArr[1])+60*60*24-1;
                $this->map[$keyword] = array('between', array($stime, $etime));
                $this->searchName[$keyword] = $value;
                $this->assign('search', $this->searchName);
            }
        }
        elseif  ($value) {
            $data = $like ? ['like', '%' . $value . '%'] : $value;
            $this->map[$keyword] = $data;
            $this->searchName[$keyword] = $value;
            $this->assign('search', $this->searchName);
        }

        return $value;
    }

    public function lqSearch($table, $key, $search_key, $like = 0, $thisKey, $vv = 0)
    {//关联查询某个字段
//        $lq = $table.'|'.$search_key;
//        if ($this->map[$lq]){
//            $value = trim(input($lq));
//            unset($this->map[$table.'|'.$search_key]);
//        }else{
//            $value = trim(input($table));
//        }
        try{
            $value = trim(input($table))?:trim(input($vv));
        }catch (\Exception $e){
            dump(input($vv));
        }

        if ($value) {
            $data = $like ? ['like', '%' . $value . '%'] : $value;
            $ids = Db::name($table)->where([$search_key => $data])->select();
            $id = $this->array_column($ids, $key);
            if (is_array($this->map[$thisKey])){
                $id = array_intersect($id,$this->map[$thisKey][1]);//找出重复的id
            }
            if (count($id) > 0) {
                $this->map[$thisKey] = ['in', $id];
            } else {
                $this->map[$thisKey] = -1;
            }
            $this->searchName[$table] = $value;
            $this->searchName[$vv] = $value;
            $this->assign('search', $this->searchName);
        }
        return $value;
    }

    function getPk($tableName){//获取主键
        $pk = \db()->getTableInfo('dlc_'.$tableName,'pk');//获取主键
        $pk = is_array($pk)?$pk[0]:$pk;
        return $pk;//获取主键，默认第一个

    }

    //获取表字段和注释
    static function get_db_column_comment($table_name = '', $field = true, $table_schema = ''){
        // 接收参数
        $database = config('database');
        $table_schema = empty($table_schema) ? $database['database'] : $table_schema;
        $table_name = $database['prefix'] . $table_name;
        // 缓存名称
        $fieldName = $field === true ? 'allField' : $field;
        $cacheKeyName = 'db_' . $table_schema . '_' . $table_name . '_' . $fieldName;
        // 处理参数
        $param = [
            $table_name,
            $table_schema
        ];
        // 字段
        $columeName = '';
        if($field !== true){
            $param[] = $field;
            $columeName = "AND COLUMN_NAME = ?";
        }
        // 查询结果
        $result = Db :: query("SELECT COLUMN_NAME as field,column_comment as comment FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = ? AND table_schema = ? $columeName", $param);
        // pp(Db :: getlastsql());

        if(empty($result) && $field !== true){
            return $table_name . '表' . $field . '字段不存在';
        }
        // 处理结果
        foreach($result as $k => $v){
            $data[$v['field']] = $v['comment'];
        }
        // 字段注释格式不正确
        if(empty($data)){
            return $table_name . '表' . $field . '字段注释格式不正确';
        }
        return count($data) == 1 ? reset($data) : $data;
    }


    //重写模板方法
    public function fetch($template = '', $vars = [], $replace = [], $config = [])
    {

        if ($template!='common/Base_bread'&&isset($this->view->list)&&isset($this->view->data)){
            //权限处理
            $data = $this->view->list;
            $list = [];
            ;            foreach ($data as $key => $item) {
                if (strstr($key,'-')){//是否有权限处理
                    $ll = explode('-',$key);
                    $key = $ll[1];
                    $res = $this->isJurisdiction($ll[0]);
                    if ($res){
                        $list[$key] = $item;
                    }
                }else{
                    $list[$key] = $item;
                }

            }
            $this->view->list = $list;
            //权限处理  end

            if (isset($this->view->list) && $this->excel){
                $list = $this->view->list;
                unset($list['sys']);

                $this->export($this->title,$list,$this->view->data);
                die;
            }
        }
        return parent::fetch($template, $vars, $replace, $config); // TODO: Change the autogenerated stub
    }

    // 添加后台角色
    public function roleEdit($roleName = false,$add_admin=false,$funName=false){
        
        $role = $roleName?:$this->className;
        $updata = ['table'=>$role,'key'=>'id'];
        $post = input('post.');
        $add['account'] = $post['phone'];
        $add['password'] = strlen($post['password'])>20?$post['password']:md5($post['password']);//判断密码长度，如果超过20 就不加密
        $noRepeat['name'] = 'phone';
        $noRepeat['tig'] = '手机号码不能重复';
        if ($add_admin && count($_POST)>0){
            $id = input('id');
            if ($id){ //更新admin表
                $role_data = Db::name($role)->find($id);
                $admin['id'] = $role_data['aid'];
                $admin['username'] = $post['phone'];
                $admin['mobile'] = $post['phone'];
                $admin['nickname'] = $post['name'];
                if ($add['password'] != $role_data['password']){
                    $admin['password'] = $add['password'];
                }
                $res = Db::name('admin')->update($admin)?:'';
                try{
                    $res = Db::name('admin')->update($admin)?:'';
                }catch (\Exception $e){
                    admin_return(0,'更新失败');
                }


            }else{
                $admin['username'] = $post['phone'];
                $admin['mobile'] = $post['phone'];
                $admin['nickname'] = $post['name'];
                $admin['password'] = $add['password'];
                $admin['ctime'] = time();
                $admin['roleid'] = $this->roleIds[$this->className];
                try{
                    $id = Db::name('admin')->insertGetId($admin);
                }catch (\Exception $e){
                    admin_return(0,'更新失败');
                }
                $add['aid'] = $id;
            }
        }

        $this->_edit($updata,$add,$noRepeat,$funName);
        echo $this->fetch('common/edit');

    }

    // 添加后台角色
    public function roleDelete($roleName = false,$id = false){
        $role = $roleName?:$this->className;
        $role_name = ['site'=>'场地','site_shop'=>'场地运营商','site_admin'=>'场地管理员','area'=>'区域负责人','device'=>'设备'];
        $depend = [
//            'site'=>[['table'=>'device','msg'=>$role_name['device'] . '绑定了' . $role_name['site'] . '，不能删除，请解绑']],
//            'site_shop'=>[
//                ['table'=>'device','msg'=>$role_name['device'] . '绑定了' . $role_name['site_shop'] . '，不能删除，请解绑'],
//                ['table'=>'site','msg'=>$role_name['site'] . '绑定了' . $role_name['site_shop'] . '，不能删除，请解绑'],
//                ['table'=>'site_admin','msg'=>$role_name['site_admin'] . '绑定了' . $role_name['site_shop'] . '，不能删除，请解绑'],
//            ],
//            'site_admin'=>[
//                ['table'=>'device','msg'=>$role_name['device'] . '绑定了' . $role_name['site_admin'] . '，不能删除，请解绑'],
//                ['table'=>'site','msg'=>$role_name['site'] . '绑定了' . $role_name['site_admin'] . '，不能删除，请解绑'],
//            ],
//            'area'=>[
//                ['table'=>'device','msg'=>$role_name['device'] . '绑定了' . $role_name['area'] . '，不能删除，请解绑'],
//                ['table'=>'site_shop','msg'=>$role_name['site_shop'] . '绑定了' . $role_name['area'] . '，不能删除，请解绑'],
//                ['table'=>'site','msg'=>$role_name['site'] . '绑定了' . $role_name['area'] . '，不能删除，请解绑'],
//                ['table'=>'site_admin','msg'=>$role_name['site_admin'] . '绑定了' . $role_name['area'] . '，不能删除，请解绑']
//            ],
        ];
        $post_id = input('id')?:input('get.id');
        $id = $id?:$post_id;
        if ($id){
            $res = Db::name($role)->find($id);
            if ($res){
                foreach ($depend[$role] as $key=>$value){
                    $resD = Db::name($value['table'])->where([$role.'_id'=>$id])->find()?:0;
                    if ($resD){
                        admin_return(0,$value['msg']);
                    }
                }
                Db::startTrans();
                try{
                    Db::name($role)->where(['id'=>$id])->delete();
                    $admin = Db::name('admin')->find($res['aid']);
                    if ($admin)Db::name('admin')->where(['id'=>$res['aid']])->delete();
                    // 提交事务
                    Db::commit();
                    admin_return(1,'删除成功');
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    admin_return(0,'删除失败');
                }



            }else{
                admin_return(0,'数据不存在');
            }
        }else{
            admin_return(0,'参数不能为空');
        }
    }
    //禁用
    public function disable()
    {
        $id = input('id');
        $data['status'] = input('status')?:2;
        if (isset($id) && isset($data['status'])){
            $msg = input('msg')?:'操作成功';
            if (input('time')){$data[input('time')] = time();}
            $controller_name = CONTROLLER_NAME;
            $res = Db::name($controller_name)->where(['id' => $id])->update($data)?:'';
            if (!empty($res) && in_array($this->className,self::$roleList)){//如果有后台账号也要禁用
                $admin_id = Db::name($controller_name)->where(['id'=>$id])->value('aid');
                Db::name('admin')->where(['id'=>$admin_id])->update(['status'=>0]);
            }

            if ($res) admin_return(1, $msg);
            admin_return(0, '失败');
        }else{
            admin_return(0,'参数不对');
        }

    }

    //-------------------------------------分组--------------------------------------------
    public function groupList(){
        $title = '分组列表';
        $this->assign('title',$title);
        $this->headBotton('','add','添加','/Dlc/'.$this->className.'/groupEdit');
        $this->headSearch('','name','分组名称','1');
        $this->listBotton('','edit','编辑','/Dlc/'.$this->className.'/groupEdit');
        $this->listBotton('','del','删除','/Dlc/'.$this->className.'/groupDel','1','确定删除');
        $this->loading('index');
        $this->search('name',1);
        $map = $this->map;
        $map['type'] = $this->className == 'user' ? 1 : 2;
        $data = model('Group')->where($map)->order('id desc')->page(self::$page)->select();
        $count = model('Group')->where($map)->count();
        $this->getPage($count, self::$psize, 'App-loader', $title, 'App-search');
        $this->assign('data',$data);
        $list = ['id' => 'ID', 'name' => '分组名称', 'sys' => '操作'];
        $this->assign('list',$list);
        echo $this->fetch('common/index');
    }
    public function groupEdit(){
        $noRepeat['name'] = 'name';
        $noRepeat['tig'] = '分组名称不能重复';
        $this->form = 'group';
        $type = $this->className == 'user' ? 1 : 2;
        $noRepeat['map'] = ['type' => $type];
        $this->backUrl = DS . MODULE_NAME . '/' . $this->className . '/groupList';
        $this->_edit(['table' => 'group', 'key' => 'id'], ['type' => $type], $noRepeat);
        echo $this->fetch('common/edit');
    }
    public function groupDel(){
        $id = input('id') ? : admin_return(-1, '缺少参数id');
        $this->_del('group', 'id', ['tableName' => 'device', 'key'=> 'id', 'msg' => '该分组下有数据，暂不能删除']);
    }
    public function getGroupData(){
        return json(model('Group')->getGroupByType($this->className));
    }
    public function groupChange(){
        $operation_id = input('post.operation_id') ? : admin_return(-1, '缺少参数operation_id');
        $group_id = input('post.group_id') ? : admin_return(-1, '请选择分组');
        if($group_row = model('Group')->getGroupByType($this->className, ['id' => $group_id])){
            $result = model(ucfirst($this->className))->save(['group_id' => $group_id], ['id' => $operation_id]);
            if($result !== false) {
                admin_return(1, '修改成功');
            }
            admin_return(0, '修改失败');
        } else {
            admin_return(0, '不存在该分组数据');
        }
    }
    //-------------------------------------------分组-----------------------------------------------

    //启用
    public function enable()
    {
        $id = input('id');
        $data['status'] = input('get.status')?:1;
        $msg = input('msg')?:'操作成功';
        if (input('time')){$data[input('get.time')] = time();}
        $controller_name = CONTROLLER_NAME;
        $res = Db::name($controller_name)->where(['id' => $id])->update($data);
        if ($res && in_array($this->className,self::$roleList)){//如果有后台账号也要开启
            $admin_id = Db::name($controller_name)->where(['id'=>$id])->value('aid');
            Db::name('admin')->where(['id'=>$admin_id])->update(['status'=>1]);
        }
        if ($res) admin_return(1, $msg);
        admin_return(0, '失败');
    }

    function iniform(){
        $this->form = $this->form?:$this->className;
        if ($this->form){
            $form = Form::get($this->form);
            if ($this->formAddArray){
                $newForm = array_merge_recursive($this->formAddArray,$form);
                foreach ($form as $key=>$value){
                    $form[$key] = $newForm[$key];
                }
            }
//            dump($form);die;
            $backUrl = $this->backUrl ? : ('dlc/' . $this->className . '/index');
            $this->assign('backUrl', $backUrl);
            $this->assign('form', $form);
            return $form;
        }else{
            return false;
        }
    }


    //编辑公用方法
    function _edit($updata = false,$add = false,$noRepeat=false,$funName=false){//$noRepeat['map'] 条件比如area_id=1     name对应的字段名     tig提示语
        $this->assign('back',$this->back);
        if (!$updata){
            if ($this->form){
                $table = Db::name('form')->where(['index_name'=>$this->form])->value('name')?:$this->className;
                $updata['table'] = $table;
                $updata['key'] = $this->getPk($table);

            }else{
                $updata['table'] = $this->className;
                $updata['key'] = $this->getPk($this->className);
            }

        }
//        $updata = ['table'=>'area','key'=>'id'];
//        $add['area_id'] = $this->map['area_id']?:0;
        $id = input('id')?:input('get.id');
        $title = ($id ? '编辑' : '添加');
        $this->assign('title', $title);
        $form = $this->iniform();
        if ($_POST){
//            \dlc\common\form\Form::check($form);
            if ($form){ Form::check($form);}
            $post = input('post.');

            $table_keys =  \db()->getTableInfo('dlc_'.$updata['table'],'fields');
            if (in_array($this->roleName.'_id',$table_keys)){
                $post[$this->roleName.'_id'] = $this->role_table_id;
            }
            if ($add)  $post = $add+$post;
            foreach ($post as $key => $item) {//判断一些上传数组的，直接转为字符串
                if (is_array($item)){
                    $post[$key] = implode(',',$item);
                }
            }
            $post = array_map('trim',$post);
            if ($id){
                if ($noRepeat){
                    $map = $noRepeat['map']?:[];
                    $map[$noRepeat['name']] = $post[$noRepeat['name']];
                    $res = Db::name($updata['table'])->where($map)->find();
                    if ($res){
                        if ($res[$updata['key']]!=$id) admin_return(0, $noRepeat['tig']?:'名称或标题重复，不可添加');
                    }
                }
//                $res = Db::name($updata['table'])->where([$updata['key']=>$id])->update($post);
                $res = model($updata['table'])->save($post,[$updata['key']=>$id]);
                if ($res){
                    if ($funName){
                        if(!method_exists($this, $funName)) {
                            admin_return(0, '方法不存在' );
                        }
                        call_user_func([$this, $funName],$id,'edit');
                    }
                }
                $res?admin_return(1, '更新成功'):admin_return(1, '数据没有修改');
            }else{
                if ($noRepeat){
                    $map = $noRepeat['map'];
                    $map[$noRepeat['name']] = $post[$noRepeat['name']];
                    $res = Db::name($updata['table'])->where($map)->find();
                    if ($res) admin_return(0, $noRepeat['tig']?:'名称或标题重复，不可添加');
                }
                $post['ctime'] = time();
//                $res = Db::name($updata['table'])->insertGetId($post);
                $boj = model($updata['table']);
                $res = $boj->save($post);
                $id = $boj[$boj->getPk()];
//                dump($id);die;
//                $res = Db::name($updata['table'])->insertGetId($post);
                if ($res){
                    if ($funName){
                        if(!method_exists($this, $funName)) {
                            admin_return(0, '方法不存在' );
                        }
                        call_user_func([$this, $funName],$id,'add');
                    }
                }
                $res?admin_return(1, '添加成功'):admin_return(0, '添加失败');
            }
        }
        if ($id) {
            $data = Db::name($updata['table'])->where([$updata['key'] => $id])->find();
            $data = $this->data?:$data;
            $this->assign('data', $data);
        }
        if (ACTION_NAME=='_edit'){
            echo $this->fetch('common/edit');
        }
    }

    //异步 修改  一定是post
    //$noRepeat['map'] 条件比如area_id=1     name对应的字段名     tig提示语
    public function _edit_ajax($updata = false,$add=false,$noRepeat=false,$funName=false){
        $id = input('id');
        $this->assign('id', $id);
        if (!$updata){
            if ($this->form){
                $table = Db::name('form')->where(['index_name'=>$this->form])->value('name')?:$this->className;
                $updata['table'] = $table;
                $updata['key'] = $this->getPk($table);
            }else{
                $updata['table'] = $this->className;
                $updata['key'] = $this->getPk($this->className);
            }
        }

        $this->form = $this->form?:$this->className;
        if ($this->form){
            $form = Form::get($this->form);
            if ($this->formAddArray){
                $newForm = array_merge_recursive($this->formAddArray,$form);

                foreach ($form as $key=>$value){
                    $form[$key] = $newForm[$key];
                }
            }
            $this->assign('form', $form);
        }
        Form::check($form);
        $post = input('post.');
        if (count($post)>1){
            if ($add)  $post = $add+$post;
            foreach ($post as $key => $item) {//判断一些上传数组的，直接转为字符串
                if (is_array($item)){
                    $post[$key] = implode(',',$item);
                }
            }
            if ($post['password']){
                $post['password'] = strlen($post['password'])>20?$post['password']:md5($post['password']);
            }
            if ($noRepeat){
                $map = $noRepeat['map']?:[];
                $map[$noRepeat['name']] = $post[$noRepeat['name']];
                $res = Db::name($updata['table'])->where($map)->find();
                if ($res){
                    if ($res[$updata['key']]!=$id) admin_return(0, $noRepeat['tig']?:'名称或标题重复，不可添加');
                }
            }

            if ($post['id']){
                $res = Db::name($updata['table'])->where([$updata['key']=>$id])->update($post);
                $action = 'edit';
            }else{
                $res = model($updata['table'])->save($post);
                $action = 'add';
            }
            if ($res){
                if ($funName){
                    if(!method_exists($this, $funName)) {
                        admin_return(0, '方法不存在' );
                    }
                    call_user_func([$this, $funName],$id,$action);
                }
            }
            $res?admin_return(1, '更新成功'):admin_return(1, '数据没有修改');
        }

        $data = Db::name($updata['table'])->where([$updata['key'] => $id])->find();
        $data = $this->data?:$data;
        $this->assign('data', $data);
        echo $this->fetch('common/ajax');
    }

    //删除公用方法
    function _del($tabelName = false,$tableKey = 'id',$child = false,$delChild = false){
        //$child = ['tableName'=>'shop','key'=>'agent_id','msg'=>'该分类下有数据，不能删除'];
//        $delChild = ['tableName'=>'2','key'=>'type_id',];
        $tabelName = $tabelName?:$this->className;
        $id = input('id')?:input('get.id');
        if ($id){
            if ($child){
                $res = Db::name($child['tableName'])->where([$child['key']=>$id])->find();
                if ($res) admin_return(0,$child['msg']?:'该分类下有数据，不能删除');
            }
            if ($delChild){
                $res = Db::name($delChild['tableName'])->where([$delChild['key']=>$id])->delete();
//                dump($res);
            }

            $res = Db::name($tabelName)->find($id);
            if ($res){
                $res = Db::name($tabelName)->where([$tableKey=>$id])->delete();
                $res?admin_return(1, '删除成功'):admin_return(0, '删除失败');
            }else{
                admin_return(0,'数据不存在');
            }
        }else{
            admin_return(0,'参数不能为空');
        }
    }

    //代理 联动
    public function agent_id(){
        $id = input('id')?:input('get.id');
        $pid = input('pid')?:input('get.pid');
        if ($id){
            $data['data'] = Db::name('agent')->where(['id'=>$id])->column('name')?:'';
            $data['code'] = 1;
            return json($data);
        }elseif ($pid){
            $data['data'] = Db::name('shop')->where(['agent_id'=>$pid])->column('id,name')?:'';
            $data['code'] = 1;
            return json($data);
        }
    }
    //商家联动
    public function shop_id(){
        $id = input('id')?:input('get.id');
        $pid = input('pid')?:input('get.pid');
        if ($id){
            $data['data'] = Db::name('shop')->where(['id'=>$id])->column('name')?:'';
            $data['code'] = 1;
            return json($data);
        }elseif ($pid){
            $data['data'] = Db::name('shop')->where(['agent_id'=>$pid])->column('id,name')?:'';
            $data['code'] = 1;
            return json($data);
        }
    }


    //省份-三级联动
    public function province(){
        $id = input('id')?:input('get.id');
        $pid = input('pid')?:input('get.pid');
        if ($id){
            $data['data'] = Db::name('location')->where(['id'=>$id])->column('name')?:'';
            $data['code'] = 1;
            return json($data);
        }elseif ($pid){
            $data['data'] = Db::name('location')->where(['pid'=>$pid])->column('id,name')?:'';
            $data['code'] = 1;
            return json($data);
        }
    }
    //城市-三级联动
    public function city(){
        $id = input('id')?:input('get.id');
        $pid = input('pid')?:input('get.pid');
        if ($id){
            $data['data'] = Db::name('location')->where(['id'=>$id])->column('name')?:'';
            $data['code'] = 1;
            return json($data);
        }elseif ($pid){
            $data['data'] = Db::name('location')->where(['pid'=>$pid])->column('id,name')?:'';
            $data['code'] = 1;
            return json($data);
        }
    }
    //城市-三级联动
    public function area(){
        $id = input('id')?:input('get.id');
        $pid = input('pid')?:input('get.pid');
        if ($id){
            $data['data'] = Db::name('location')->where(['id'=>$id])->column('name')?:'';
            $data['code'] = 1;
            return json($data);
        }elseif ($pid){
            $data['data'] = Db::name('location')->where(['pid'=>$pid])->column('id,name')?:'';
            $data['code'] = 1;
            return json($data);
        }
    }

    function getCheck(){
        $ids = input('ids');
        if (empty($ids)){
            admin_return(0,'请勾选');
        }
        return explode(',',$ids);
    }



    function array_column(array $array, $column_key, $index_key = null)
    {
        $result = [];
        foreach ($array as $arr) {
//            if (!is_array($arr)) continue;

            if (is_null($column_key)) {
                $value = $arr;
            } else {
                $value = $arr[$column_key];
//                dump($value);
            }

            if (!is_null($index_key)) {
                $key = $arr[$index_key];
                $result[$key] = $value;
            } else {
                $result[] = $value;
            }
        }
        return $result;
    }

    /**
     * [export 导出数据]
     * @Author   Lar
     * @DateTime 2018-05-11
     * @param    [type]     $filename   [导出的文件名]
     * @param    [type]     $head_field [字段中文名]
     * @param    [type]     $data_field [数据库字段名]
     * @param    [type]     $data       [数据源]
     * @return   [type]                 [description]
     */
    function export($filename,$list,$data){

        header("Content-Type: text/html;charset=GB2312");
        if(!$filename || !$list) {
            echo "error";die();
        }
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment;filename=".$filename.".xls");
        header('Cache-Control: max-age=0');
        echo "<table bordercolor='gray' border='1' cellspacing='0' style='border-collapse:collapse;font-family:微软雅黑'>";
        echo "<tr>";
        foreach($list as $k=>$v){
            echo "<th>".iconv("UTF-8", "GB2312//IGNORE", $v)."</th>";
            //echo "<th>".$v."</th>";
        }
        echo "</tr>";
	if ($data){

        foreach($data as $d){
            echo "<tr>";
            foreach($list as $k=>$v){
                if (strstr($k,'|')){
                    $lists = explode('|',$k);
                    $a = $d;
                    foreach ($lists as $key=>$value){
                        $a = $a[$value];
                    }
                    $td = $a?:'/';
                }else{
                    if (strstr($k,'time')){
                        if (strlen($d[$k])==10){
                            $d[$k] = date('Y-m-d H:i:s',$d[$k]);
                        }
                    }
                    $td = $d[$k];
                    if (is_array($d[$k])){
                        $td = implode("," ,$d[$k] );
                    }
                }


//                dump($d[$k]);
//                die;
                echo "<td style=vnd.ms-excel.numberformat:@>".iconv("UTF-8", "GB2312//IGNORE", $td)."</td>";
//                echo "<td style=vnd.ms-excel.numberformat:@>".$td."</td>";
            }
            echo "</tr>";
 		}
        }
        echo "</table>";
    }
    /**
    　　* 下划线转驼峰
    　　* 思路:
    　　* step1.原字符串转小写,原字符串中的分隔符用空格替换,在字符串开头加上分隔符
    　　* step2.将字符串中每个单词的首字母转换为大写,再去空格,去字符串首部附加的分隔符.
    　　*/
    function camelize($uncamelized_words,$first=false,$separator='_')
    {
        $uncamelized_words = $separator. str_replace($separator, " ", strtolower($uncamelized_words));
        $data =  ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator );
        if ($first){
            $data = ucfirst($data);
        }
        return $data;
    }

    /**
    　* 驼峰命名转下划线命名
    　　* 思路:
    　　* 小写和大写紧挨一起的地方,加上分隔符,然后全部转小写
    　　*/
    function uncamelize($camelCaps,$separator='_')
    {
        return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
    }




}

